package servlet;

import entity.User;
import service.UserService;
import service.UserServiceImpl;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "adminLoginServlet",urlPatterns = "/adminLoginServlet")
public class adminLoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                String userName = request.getParameter("userName");
                String password = request.getParameter("password");
                UserService userService = new UserServiceImpl();
                User user = userService.userLoginService(new User(userName, password));
                if (null == user) {
                    System.out.println("登陆失败");
                    request.setAttribute("error", "登录失败，用户名或者密码错误");
                    request.getRequestDispatcher("index.jsp").forward(request, response);

                } else {
                    // 通过服务器跳转的方式 实现内部Servlet之间的跳转
                    request.getSession().setAttribute("userName", "admin");
                    Cookie cookie = new Cookie("login", "admin");
                    System.out.println("登录成功，欢迎使用！");
                    response.addCookie(cookie);
                    System.out.println("添加login的cookie成功");
                    cookie.setMaxAge(7 * 24 * 60 * 60);
                    System.out.println("设置cookie时间成功");
                    response.sendRedirect("studentPageQueryServlet");

                }
            }



    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}
